using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class StatsBar : MonoBehaviour
{
    private Canvas canvas;
    private float currentFillValue;
    private float targeFillValue;
    private float t;
    [SerializeField]private Image fillImageBack;
    [SerializeField]private Image fillImageFort;
    [SerializeField]private float fillSpeed;
    Coroutine coroutine;
    private void Update()
    {
        transform.LookAt(Camera.main.transform);
    }
    private void Start()
    {
        canvas = GetComponent<Canvas>();
        canvas.worldCamera = Camera.main;
    }

    public void Initialize(float minValue,float maxValue)
    {
        currentFillValue = minValue / maxValue;
        targeFillValue = currentFillValue;
        fillImageBack.fillAmount = currentFillValue;
        fillImageFort.fillAmount = currentFillValue;
    }
    public void UpdateStart(float minValue, float maxValue)
    {
        if (coroutine != null)
        {
            StopCoroutine(coroutine);
        }
        targeFillValue = minValue / maxValue;
        if (currentFillValue > targeFillValue)
        {
            fillImageFort.fillAmount = targeFillValue;
            coroutine=StartCoroutine(BufferedFillingStart(fillImageBack));
        }
        if (currentFillValue < targeFillValue)
        {
            fillImageBack.fillAmount = targeFillValue;
            coroutine=StartCoroutine(BufferedFillingStart(fillImageFort));
        }
    }
  
    IEnumerator BufferedFillingStart(Image image)
    {
        t = 0f;
        while(t<1f)
        {
            t += Time.deltaTime * fillSpeed;
            currentFillValue = Mathf.Lerp(currentFillValue,targeFillValue,t);
            image.fillAmount = currentFillValue;
            yield return null;
        }
    }
}
